#!/usr/bin/env python3
# -*- coding=utf-8 -*-
# 本脚由亁颐堂现任明教教主编写，用于乾颐盾Python课程！
# 教主QQ:605658506
# 亁颐堂官网www.qytang.com
# 教主技术进化论拓展你的技术新边疆
# https://ke.qq.com/course/271956?tuin=24199d8a

# import django
# import os
# os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'DevNet2019.settings')
# django.setup()
from devnet.models import Devicedb, DeviceInterface, DeviceInterfaceState, DeviceInterfaceSpeed, DeviceInterfaceInBytes, DeviceInterfaceOutBytes
from devnet.models import Thresholdutilization
from devnet.models import LastAlarmUtilization
from devnet.modules.qyt_devnet_0_snmp_get import get_interface_info
from datetime import datetime
from devnet.modules.qyt_devnet_0_smtp import alarm_msg


def get_utilization_threshold():
    try:
        utilization_threshold_obj = Thresholdutilization.objects.get(id=1)
        threshold = utilization_threshold_obj.utilization_threshold
        if not threshold:
            return False
        else:
            interval = utilization_threshold_obj.alarm_interval
            if not interval:
                return False
            else:
                return threshold, interval
    except Thresholdutilization.DoesNotExist:
        return False


def get_utilization_last_alarm(interface_obj):
    if not get_utilization_threshold():
        return False
    interval = get_utilization_threshold()[1]
    try:
        last_alarm = LastAlarmUtilization.objects.get(interface=interface_obj).last_alarm_datetime
        if (datetime.now() - last_alarm).seconds > (interval * 60):
            l = LastAlarmUtilization.objects.get(interface=interface_obj)
            l.last_alarm_datetime = datetime.now()
            l.save()
            return True
        else:
            return False
    except LastAlarmUtilization.DoesNotExist:
        c = LastAlarmUtilization(interface=interface_obj)
        c.save()
        return True


def get_interface_todb():
    for device in Devicedb.objects.all():
        try:
            if device.reachable.all().order_by('-id')[0].snmp_reachable:
                interface_info_list = get_interface_info(device.ip)
                for x in interface_info_list:
                    try:
                        i = DeviceInterface.objects.get(device=device, interface_name=x.get('name'))
                        i.interface_speed.speed = x.get('speed')
                        i.interface_speed.save()
                    except DeviceInterface.DoesNotExist:
                        i = DeviceInterface(device=device, interface_name=x.get('name'))
                        i.save()
                        interface_speed = DeviceInterfaceSpeed(interface=i, speed=x.get('speed'))
                        interface_speed.save()

                    interface_state = DeviceInterfaceState(interface=i, state=x.get('state'))
                    interface_state.save()
                    in_bytes = DeviceInterfaceInBytes(interface=i, in_bytes=x.get('in_bytes'))
                    in_bytes.save()
                    if get_utilization_threshold():
                        if DeviceInterfaceInBytes.objects.filter(interface=i):
                            last_record = DeviceInterfaceInBytes.objects.filter(interface=i).order_by('-id')
                            last_0_bytes = last_record[0].in_bytes
                            last_0_time = last_record[0].record_datetime
                            last_1_bytes = last_record[1].in_bytes
                            last_1_time = last_record[1].record_datetime
                            utilization_now = (((last_0_bytes - last_1_bytes) * 8) / (last_0_time - last_1_time).seconds / x.get('speed')) * 100
                            if utilization_now > get_utilization_threshold()[0]:
                                if get_utilization_last_alarm(i):
                                    alarm_msg("设备{0} 接口{1} 入向利用率超过阈值{2}%!当前的利用率为{3}%".format(device.name, i.interface_name, get_utilization_threshold()[0], round(utilization_now, 2)))
                    out_bytes = DeviceInterfaceOutBytes(interface=i, out_bytes=x.get('out_bytes'))
                    out_bytes.save()
                    if get_utilization_threshold():
                        if DeviceInterfaceOutBytes.objects.filter(interface=i):
                            last_record = DeviceInterfaceOutBytes.objects.filter(interface=i).order_by('-id')
                            last_0_bytes = last_record[0].out_bytes
                            last_0_time = last_record[0].record_datetime
                            last_1_bytes = last_record[1].out_bytes
                            last_1_time = last_record[1].record_datetime
                            utilization_now = (((last_0_bytes - last_1_bytes) * 8) / (last_0_time - last_1_time).seconds / x.get('speed')) * 100
                            if utilization_now > get_utilization_threshold()[0]:
                                if get_utilization_last_alarm(i):
                                    alarm_msg("设备{0} 接口{1} 出向利用率超过阈值{2}%!当前的利用率为{3}%".format(device.name, i.interface_name, get_utilization_threshold()[0], round(utilization_now, 2)))

            else:
                continue
        except Exception:
            continue


if __name__ == '__main__':
    # print(get_utilization_threshold())
    get_interface_todb()
